package cn.dogger.easyboot.druid.config;

import cn.dogger.easyboot.druid.enums.DataSourceEnum;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置文件
 * @author DOGGER-001
 */
@Configuration
public class DruidConfig{
    /**
     * 从数据源
     */
    @Bean
    @ConditionalOnProperty(prefix = "spring.datasource.druid.servant",name = "enabled",havingValue = "true")
    public DataSource servantDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 从数据源
     * @return DataSource
     */
    @Bean
    @ConditionalOnProperty(prefix = "spring.datasource.druid.third",name = "enabled",havingValue = "true")
    public DataSource thirdDataSource(){
        return DruidDataSourceBuilder.create().build();
    }


    /**
     * 主数据源
     * @return DataSource
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
    public DataSource masterDataSource(){
        return DruidDataSourceBuilder.create().build();
    }
    //后续更多数据源这里加....然后配置文件加.....


    /**
     * 默认加载配置
     * 添加数据源
     * 配置了多少个就添加多少个
     * 名称对应配置的方法名
     * @param masterDataSource  主数据源
     * @param servantDataSource 从数据源
     * ......
     */
    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource,DataSource servantDataSource,DataSource thirdDataSource){
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceEnum.MASTER, masterDataSource);
        targetDataSources.put(DataSourceEnum.SERVANT, servantDataSource);
        targetDataSources.put(DataSourceEnum.THIRD, thirdDataSource);
        // 还有数据源,在targetDataSources中继续添加
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
}
